<template>
  <div class="body">
    <div id="login_box" v-loading="loading" element-loading-text="正在登录...">
      <h2>人事管理系统</h2>
      <div id="input_box">
        <input type="text" v-model="username" placeholder="请输入用户名">
      </div>
      <div class="input_box">
        <input type="password" v-model="password" placeholder="请输入密码">
      </div>
      <button @click="loginRequest">登录</button>
      <br>
    </div>
  </div>
</template>

<script setup>
import {ref} from "vue";
import {ElNotification} from "element-plus";
import router from "@/router/index.js";
import {login} from "@/api/user.js";

const username = ref('')
const password = ref('')
const loading = ref(false)

const loginRequest = async () => {
  loading.value = true; // 开始加载
  const data = {
    username: username.value,
    password: password.value,
  };

  try {
    const res = await login(data); // 调用登录接口

    if (res.code !== 200) {
      // 登录失败
      ElNotification({
        title: '登录失败',
        message: '用户名或密码错误！',
        type: 'error',
      });

      password.value = ''; // 清空密码输入框
      loading.value = false; // 停止加载
      return;
    }

    // 登录成功
    localStorage.setItem('token', res.data.token); // 存储 token
    localStorage.setItem('userInfo', JSON.stringify(res.data.usersVo)); // 存储用户信息
    await router.push('/home'); // 跳转到首页
  } catch (error) {
    // 处理请求异常
    ElNotification({
      title: '登录失败',
      message: '请求异常，请稍后重试！',
      type: 'error',
    });
  } finally {
    loading.value = false; // 无论成功或失败，停止加载
  }
};

</script>

<style scoped>
.body {
  background: url('https://cdn.pixabay.com/photo/2018/08/14/13/23/ocean-3605547_1280.jpg') no-repeat;
  background-size: 100% 130%;
  display: flex;
  justify-content: center;
  align-items: center;
  flex-direction: column;

}

#login_box {
  width: 20%;
  height: 400px;
  background-color: #00000060;
  margin: 10% auto auto;
  text-align: center;
  border-radius: 10px;
  padding: 50px 50px;
}

h2 {
  color: #ffffff90;
  margin-top: 5%;
}

#input-box {
  margin-top: 5%;
}

span {
  color: #fff;
}

input {
  border: 0;
  width: 60%;
  font-size: 15px;
  color: #fff;
  background: transparent;
  border-bottom: 2px solid #fff;
  padding: 5px 10px;
  outline: none;
  margin-top: 10px;
}

button {
  margin-top: 50px;
  width: 60%;
  height: 30px;
  border-radius: 10px;
  border: 0;
  color: #fff;
  text-align: center;
  line-height: 30px;
  font-size: 15px;
  background-image: linear-gradient(to right, #30cfd0, #330867);
}

#sign_up {
  margin-top: 45%;
  margin-left: 60%;
}

a {
  color: #b94648;
}

.example-showcase .el-loading-mask {
  z-index: 999;
}
</style>
